﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;

/// <summary>
/// 摄像机视角的控制.
/// </summary>
public class CameraView : MonoBehaviour
{
    private static CameraView _instance;
    public static CameraView Instance
    {
        get { return _instance; }
    }

    private void Awake()
    {
        _instance = this;
        InitWidget();
    }

    private PlayerCharacter _player;

    private void InitWidget()
    {
        //TODO:肯定会改角色的.
        _player = FindObjectOfType<PlayerCharacter>();
    }

    private readonly float _rotateTime = 0.1f;
    private float _rotateTimeCounter;

    private bool _canRotate = true;

    /// <summary>
    /// 改变视角.
    /// </summary>
    public void ChangeView(int dir)
    {
        if (!_canRotate)
        {
            return;
        }
        //transform.RotateAround(Vector3.zero, Vector3.up, 90);
        _player.SetSrc();
        _player.ChangeFaceState(dir);
        
        StartCoroutine(ChangingView(dir));
        //_player.ChangePos();
        //改变角色朝向的枚举.
        
    }

    private IEnumerator ChangingView(int dir)
    {
        _canRotate = false;
        _player.ChangeGravityState(false);
        _player.SetTriggerState(true);
        _rotateTimeCounter = _rotateTime;
        while (_rotateTimeCounter > 0)
        {
            _rotateTimeCounter -= _rotateTime / 90;
            //TODO:角度控制改变方向.
            transform.RotateAround(Vector3.zero, Vector3.up, -1 * dir);
            //Debug.Log(Camera.main.WorldToViewportPoint(_player._collideTransform.position));
            _player.ChangePos();
            yield return new WaitForSeconds(_rotateTime / 90);
        }

        _canRotate = true;
        _player.ChangeGravityState(true);
        _player.SetTriggerState(false);
    }

    private Vector3 _playerPos;

    public void Rotating()
    {
        _player.transform.SetParent(this.transform);
        StartCoroutine(RotateColumn());
        //上升.
        transform.DOMoveY(38.0f, 25f);
        
    }

    private IEnumerator RotateColumn()
    {
        while (true)
        {
            transform.RotateAround(Vector3.zero, Vector3.up, 1);
            yield return new WaitForSeconds(_rotateTime / 90);
        }
    }
    
}
